package com.example.musicdemo.service

import android.annotation.TargetApi
import android.app.*
import android.content.Context
import android.content.Intent
import android.graphics.BitmapFactory
import android.media.MediaPlayer
import android.os.Binder
import android.os.Build
import android.os.IBinder
import android.widget.RemoteViews
import androidx.core.app.NotificationCompat
import com.example.musicdemo.R
import com.example.musicdemo.model.AudioBean
import com.example.musicdemo.ui.activity.AudioPlayActivity
import com.example.musicdemo.ui.activity.MainActivity
import org.greenrobot.eventbus.EventBus
import java.util.*

class AudioService : Service() {
    var mMediaPlayer: MediaPlayer? = null
    var mList: ArrayList<AudioBean>? = null
    var mManager: NotificationManager? = null
    var mNotification: Notification? = null
    private val mBinder by lazy { AudioBinder() }
    var mPosition: Int = -2
    val mSp by lazy { getSharedPreferences("config", Context.MODE_PRIVATE) }
    var mode = MODE_ALL  //播放模式


    companion object {
        //播放全部
        const val MODE_ALL = 1
        const val MODE_SINGLE = 2
        const val MODE_RANDOM = 3

        const val FROM_PRE = 1
        const val FROM_NEXT = 2
        const val FROM_STATE = 3
        const val FROM_CONTENT = 4
    }

    override fun onCreate() {
        super.onCreate()
        //获取播放模式
        mode = mSp.getInt("mode", 1)
    }

    override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
        //判断进入service方法
        val from = intent?.getIntExtra("from",-1)
        println("kankan这看看那些")
        when (from) {
            FROM_PRE -> {
                mBinder.playPre()
            }
            FROM_NEXT -> {
                mBinder.playNext()
            }
            FROM_CONTENT -> {
                mBinder.notifyUpdateUi()
            }
            FROM_STATE -> {
                mBinder.updatePlayState()
            }
            //否则就是活动跳进来的
            else -> {
                //想要播放的position
                val pos = intent?.getIntExtra("position", -1) ?: -1
                if (pos != mPosition) {
                    //想要播放的条目和正在播放条目不是同一首
                    mPosition = pos
                    //获取集合以及position
                    println("kankan ${intent?.getParcelableArrayListExtra<AudioBean>("list")}")
                    mList = intent?.getParcelableArrayListExtra("list")
                    mBinder.playItem()
                } else {
                    mBinder.notifyUpdateUi()
                }
            }
        }
        //START_STICKY   粘性的  service强制杀死之后 会尝试重新启动service 不会传递原来的intent(null)
        //START_NOT_STICKY 非粘性的 service强制杀死之后 不会尝试重新启动service
        //START_REDELIVER_INTENT service强制杀死之后 会尝试重新启动service  会传递原来的intent
        return START_NOT_STICKY

    }

    override fun onBind(intent: Intent?): IBinder? {
        return mBinder
    }

    inner class AudioBinder : Binder(), IService, MediaPlayer.OnPreparedListener,
        MediaPlayer.OnCompletionListener {
        override fun updatePlayState() {
            val isPlaying = isPlaying()
            //切换播放状态
            isPlaying?.let {
                if (isPlaying) {
                    pause()
                } else {
                    start()
                }
            }
        }

        private fun start() {
            mMediaPlayer?.start()
            EventBus.getDefault().post(mList?.get(mPosition))
            mNotification?.contentView?.setImageViewResource(
                R.id.state,
                R.drawable.btn_audio_play_normal
            )
            mManager?.notify(1, mNotification)
        }

        private fun pause() {
            mMediaPlayer?.pause()
            EventBus.getDefault().post(mList?.get(mPosition))
            //更新图
            mNotification?.contentView?.setImageViewResource(
                R.id.state,
                R.drawable.btn_audio_pause_normal
            )
            //重新显示
            mManager?.notify(1, mNotification)

        }


        override fun isPlaying(): Boolean? {
            return mMediaPlayer?.isPlaying
        }

        override fun getDuration(): Int {
            return mMediaPlayer?.duration ?: 0
        }

        override fun getProgress(): Int {
            return mMediaPlayer?.currentPosition ?: 0
        }

        override fun seekTo(p1: Int) {
            mMediaPlayer?.seekTo(p1)
        }

        /**
         * 修改播放模式
         */
        override fun updatePlayMode() {
            when (mode) {
                MODE_ALL -> mode = MODE_SINGLE
                MODE_SINGLE -> mode = MODE_RANDOM
                MODE_RANDOM -> mode = MODE_ALL
            }
            mSp.edit().putInt("mode", mode).apply()
        }

        /**
         * 播放上一首歌曲
         *
         */
        override fun playPre() {
            mList?.let {
                when (mode) {
                    MODE_RANDOM -> mList?.let {
                        mPosition = Random().nextInt(it.size - 1)
                    }
                    else -> {
                        if (mPosition == 0) {
                            mPosition = it.size - 1
                        } else {
                            mPosition--
                        }
                    }
                }
                playItem()
            }
        }


        /**
         * 播放上一首歌曲
         */
        override fun playNext() {
            mList?.let {
                mPosition = when (mode) {
                    MODE_RANDOM -> Random().nextInt(it.size - 1)
                    else -> (mPosition + 1) % it.size
                }
            }
            playItem()
        }

        /**
         * 获取播放集合
         */
        override fun getPlayList(): List<AudioBean>? {
            return mList
        }

        /**
         * 播放当前位置的歌曲
         */
        override fun playPosition(position: Int) {
            this@AudioService.mPosition = position
            playItem()
        }

        /**
         * 获得播放模式
         */
        override fun getPlayMode(): Int {
            return mode
        }

        override fun onPrepared(mp: MediaPlayer?) {
            start()
            notifyUpdateUi()
            showNotification()
        }

        private fun showNotification() {
            mManager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
            initNotification()
        }


        /**
         * 创建通知渠道
         *
         * @param channelId   渠道id
         * @param channelName 渠道名称
         * @param importance  渠道重要性
         */
        @TargetApi(Build.VERSION_CODES.O)
        private fun createNotificationChannel(
            channelId: String,
            channelName: String,
            importance: Int
        ) {
            val channel = NotificationChannel(channelId, channelName, importance)
            channel.enableLights(false)
            channel.enableVibration(false)
            channel.vibrationPattern = longArrayOf(0)
            channel.setSound(null, null)
            //获取系统通知服务
            mManager =
                getSystemService(NOTIFICATION_SERVICE) as NotificationManager
            mManager!!.createNotificationChannel(channel)
        }


        /**
         * 初始化通知
         */
        private fun initNotification() {
            val channelId = "play_control"
            val channelName = "播放控制"
            val importance = NotificationManager.IMPORTANCE_HIGH
            createNotificationChannel(channelId, channelName, importance)
/*
            //点击整个通知时发送广播
            val intent = Intent(applicationContext, NotificationClickReceiver::class.java)*/
/*            val pendingIntent = PendingIntent.getBroadcast(
                applicationContext, 0,
                intent, PendingIntent.FLAG_UPDATE_CURRENT
            )*/

            //初始化通知
            mNotification =
                NotificationCompat.Builder(applicationContext, "play_control")
//                    .setContentIntent(pendingIntent)
                    .setOngoing(true)//设置不能滑动删除通知
                    .setContentIntent(getPendingIntent())//通知栏主体点击事件
                    .setCustomContentView(getRemoteViews())

                    .setWhen(System.currentTimeMillis())
                    .setSmallIcon(R.mipmap.ic_launcher_round)
                    .setLargeIcon(BitmapFactory.decodeResource(resources, R.mipmap.ic_launcher))
//                    .setCustomContentView(com.example.musicapp.service.MediaService.remoteViews)
                    .setPriority(NotificationCompat.PRIORITY_MAX)
                    .setVisibility(NotificationCompat.VISIBILITY_PUBLIC)
                    .setAutoCancel(false)
                    .setOnlyAlertOnce(true)
                    .build()
        }

        private fun getRemoteViews(): RemoteViews? {
            val remoteViews = RemoteViews(packageName, R.layout.notification)
            remoteViews.setTextViewText(R.id.title, mList?.get(mPosition)?.display_name)
            remoteViews.setTextViewText(R.id.artist, mList?.get(mPosition)?.artist)

            //处理上一首 下一首
            remoteViews.setOnClickPendingIntent(R.id.pre, getPrePendingIntent())
            remoteViews.setOnClickPendingIntent(R.id.state, getStatePendingIntent())
            remoteViews.setOnClickPendingIntent(R.id.next, getNextPendingIntent())
            return remoteViews
        }

        /**
         * 通知栏下一首
         */
        private fun getNextPendingIntent(): PendingIntent? {
            val intent = Intent(this@AudioService, AudioService::class.java)
            intent.putExtra("from", FROM_NEXT)
            return PendingIntent.getService(
                this@AudioService, 2, intent,
                PendingIntent.FLAG_UPDATE_CURRENT
            )
        }


        /**
         * 播放按钮暂停时候调用
         */
        private fun getStatePendingIntent(): PendingIntent? {
            val intent = Intent(this@AudioService, AudioService::class.java)
            intent.putExtra("from", FROM_STATE)
            return PendingIntent.getService(
                this@AudioService, 3,
                intent, PendingIntent.FLAG_UPDATE_CURRENT
            )
        }

        /**
         * 通知栏上一首操作
         */
        private fun getPrePendingIntent(): PendingIntent? {
            //点击主题注入当前界面
            val intent = Intent(this@AudioService, AudioService::class.java)
            intent.putExtra("from", FROM_PRE)
            return PendingIntent.getService(
                this@AudioService, 4, intent,
                PendingIntent.FLAG_UPDATE_CURRENT
            )
        }


        /**
         * 通知栏主题点击事件
         */
        private fun getPendingIntent(): PendingIntent? {
            //点击主体进入到当前界面
            val intentM = Intent(this@AudioService, MainActivity::class.java)
            val intentA = Intent(this@AudioService, AudioPlayActivity::class.java)
            intentA.putExtra("from", FROM_CONTENT)
            val intents = arrayOf(intentM, intentA)
            return PendingIntent.getActivities(
                this@AudioService,
                1,
                intents,
                PendingIntent.FLAG_UPDATE_CURRENT
            )
        }


        /**
         * 播放完一首歌会调用的方法
         */
        override fun onCompletion(mp: MediaPlayer?) {
            autoPlayNext()
        }

        /**
         * 自动播放下一首 要根据播放模式
         */
        private fun autoPlayNext() {
            when (mode) {
                MODE_ALL -> {
                    mList?.let {
                        mPosition = (mPosition + 1) % it.size
                    }

                }
                MODE_RANDOM -> mList?.let {
                    mPosition = Random().nextInt(it.size)
                }

            }
            playItem()
        }

        /**
         * 通知界面更新
         */
        fun notifyUpdateUi() {
            EventBus.getDefault().post(mList?.get(mPosition))
        }

        fun playItem() {
            //假如mediaPlayer已经存在就先释放掉
            if (mMediaPlayer != null) {
                mMediaPlayer?.reset()
                mMediaPlayer?.release()
                mMediaPlayer = null
            }
            mMediaPlayer = MediaPlayer()
            mMediaPlayer?.let {


                it.setOnPreparedListener(this)
                it.setOnCompletionListener(this)
                println("饿${mList}   kankan这$mMediaPlayer")
                it.setDataSource(mList?.get(mPosition)?.data)
                it.prepareAsync()
            }
        }


    }
}